/**
 * 
 */
package com.antilia.infomaresme.form;

import java.util.List;

import org.apache.wicket.Component;
import org.apache.wicket.Session;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.feedback.ComponentFeedbackMessageFilter;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.IFormSubmittingComponent;
import org.apache.wicket.request.Response;

/**
 * @author Ernesto Reinaldo Barreiro
 */
public class ValidationMessageBehavior extends Behavior {
	
	private static final long serialVersionUID = 1L;

	private boolean wantHelpTooltips;
	
	private boolean validationMessage;
		
	/**
	 * Constructor.
	 */
	public ValidationMessageBehavior(boolean wantHelpTooltips, boolean validationMessage) {
		this.wantHelpTooltips = wantHelpTooltips;
		this.validationMessage = validationMessage;
	}
	
	@Override
	public void beforeRender(Component component) {
		super.beforeRender(component);		
		FormComponent<?> fc = (FormComponent<?>) component;
		if (!fc.isValid()) {
			if(!(fc instanceof IFormSubmittingComponent)) {
				Response r = component.getResponse();
				String id= fc.getMarkupId()+"_trigger";
				r.write("<span id=\""+id+"\" class=\"ErrorInd\">*</span>");
				if (validationMessage) {
					StringBuffer error = new StringBuffer();
					if (fc.hasFeedbackMessage()) {
						List<FeedbackMessage> mesages = Session.get().getFeedbackMessages().messages(new ComponentFeedbackMessageFilter(fc));
						//error.append("<ol>");				
						for(FeedbackMessage message : mesages) {
							error.append("<span>");
							error.append(message.getMessage().toString());
							error.append("</span>");
						}
						//error.append("</ol>");
					} else {
						error.append("Your input is invalid.");
					}
					fc.getResponse().write(
					"<span class=\"smallTip\">" + error + "</span>");						
				}		
			}
		} else if(!(fc instanceof IFormSubmittingComponent)) {
			Response r = component.getResponse();
			r.write("<span class=\"ErrorInd\">&nbsp;&nbsp;</span>");
		}
	}
	
	@Override
	public void afterRender(Component component) {
		FormComponent<?> fc = (FormComponent<?>)component;		
		if(wantHelpTooltips) {
			String key = fc.getId() + ".help";
			String help = fc.getString(key, null, key);
			fc.getResponse().write("<span class=\"smallTip\">"+help+"</span>");
		}
	}
	
	public boolean isTemporary(Component component) {
		return true;
	};

}
